package com.powernode.dispatch.handler;

import com.powernode.dispatch.mapper.XxlJobLogMapper;
import com.powernode.dispatch.service.NewOrderService;
import com.powernode.model.entity.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.springframework.stereotype.Component;

/**
 * 用户下单后执行的任务
 */
@Component
public class JobHandler {

    @Resource
    private XxlJobLogMapper xxlJobLogMapper;

    @Resource
    private NewOrderService newOrderService;

    @XxlJob("newOrderTaskHandler")
    public void newOrderTaskHandler(){
        //日志
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());

        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            newOrderService.executeTask(XxlJobHelper.getJobId());

            //成功
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            xxlJobLog.setStatus(0);//失败
            xxlJobLog.setError("订单任务执行失败");
            e.printStackTrace();
        }finally {
            long endTime = System.currentTimeMillis();
            int duration = (int)(endTime - startTime);//执行耗时
            xxlJobLog.setTimes(duration);
            xxlJobLogMapper.insert(xxlJobLog);
        }


    }

}
